using System;
using Volo.Abp.Domain.Entities.Auditing;
using Volo.Abp.MultiTenancy;

namespace AuthService.Domain.Auth;

/// <summary>
/// 认证会话实体
/// </summary>
public class AuthSession : FullAuditedAggregateRoot<Guid>, IMultiTenant
{
    /// <summary>
    /// 租户ID
    /// </summary>
    public virtual Guid? TenantId { get; set; }

    /// <summary>
    /// 用户ID
    /// </summary>
    public virtual Guid UserId { get; set; }

    /// <summary>
    /// 会话令牌
    /// </summary>
    public virtual string SessionToken { get; set; } = string.Empty;

    /// <summary>
    /// 访问令牌ID
    /// </summary>
    public virtual Guid AccessTokenId { get; set; }

    /// <summary>
    /// 刷新令牌ID
    /// </summary>
    public virtual Guid? RefreshTokenId { get; set; }

    /// <summary>
    /// 登录时间
    /// </summary>
    public virtual DateTime LoginTime { get; set; }

    /// <summary>
    /// 过期时间
    /// </summary>
    public virtual DateTime ExpiresAt { get; set; }

    /// <summary>
    /// 最后活动时间
    /// </summary>
    public virtual DateTime LastActivityTime { get; set; }

    /// <summary>
    /// IP地址
    /// </summary>
    public virtual string IpAddress { get; set; } = string.Empty;

    /// <summary>
    /// 用户代理
    /// </summary>
    public virtual string UserAgent { get; set; } = string.Empty;

    /// <summary>
    /// 设备信息
    /// </summary>
    public virtual string DeviceInfo { get; set; } = string.Empty;

    /// <summary>
    /// 是否活跃
    /// </summary>
    public virtual bool IsActive { get; set; } = true;

    /// <summary>
    /// 登出时间
    /// </summary>
    public virtual DateTime? LogoutTime { get; set; }

    /// <summary>
    /// 登出原因
    /// </summary>
    public virtual string LogoutReason { get; set; } = string.Empty;

    /// <summary>
    /// 设备ID
    /// </summary>
    public virtual string DeviceId { get; set; } = string.Empty;

    /// <summary>
    /// 创建时间（别名属性，用于兼容）
    /// </summary>
    public virtual DateTime CreatedAt => LoginTime;

    protected AuthSession()
    {
    }

    public AuthSession(Guid id, Guid userId, string sessionToken, Guid accessTokenId) : base(id)
    {
        UserId = userId;
        SessionToken = sessionToken;
        AccessTokenId = accessTokenId;
        LoginTime = DateTime.Now;
        LastActivityTime = DateTime.Now;
    }

    /// <summary>
    /// 更新最后活动时间
    /// </summary>
    public virtual void UpdateLastActivity()
    {
        LastActivityTime = DateTime.Now;
    }

    /// <summary>
    /// 检查会话是否过期
    /// </summary>
    public virtual bool IsExpired()
    {
        return DateTime.Now > ExpiresAt;
    }

    /// <summary>
    /// 注销会话
    /// </summary>
    public virtual void Logout(string reason = "")
    {
        IsActive = false;
        LogoutTime = DateTime.Now;
        LogoutReason = reason;
    }
}